package com.b511.swpu.cementbackend.repository;

import com.b511.swpu.cementbackend.entity.MetaDict;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;
import java.util.stream.Stream;

public interface MetaDictRepository extends JpaRepository<MetaDict, Long> {

    //    @Query(value = "SELECT MAX (CODE) FROM META_DICT", nativeQuery = true)
    @Query(value = "SELECT MAX (md.code) FROM MetaDict md WHERE LENGTH(md.code)=:level1CodeLength")
    String findMaxLevel1Code(@Param("level1CodeLength") int level1CodeLength);

    //    @Query(value = "SELECT MAX (CODE) FROM META_DICT WHERE SUBSTR(CODE, 0, ?1)=?2", nativeQuery = true)
    @Query(value = "SELECT MAX (md.code) FROM MetaDict md WHERE SUBSTRING(md.code, 0, :parentCodeLength) = :parentCode")
    String findMaxLevel2Code(@Param("parentCodeLength") int parentCodeLength, @Param("parentCode") String parentCode);

    Integer deleteByCode(String code);

    //    @Query(value = "SELECT ID,CODE,NAME FROM META_DICT WHERE LENGTH(code)=?1", nativeQuery = true)
    @Query(value = "SELECT md FROM MetaDict md WHERE LENGTH(code)=:codeLength")
    Stream<MetaDict> findParentDict(@Param("codeLength") int codeLength);

    @Modifying
    @Query("UPDATE MetaDict md SET md.label = :label WHERE md.code = :code")
    void updateDictName(@Param("code") String code, @Param("label") String label);

    MetaDict findByLabel(String label);

    List<MetaDict> findByCodeStartingWithAndLabelNot(String parentCode, String label);

    Integer countByCodeStartingWith(String parentCode);
}
